package ufc.web.funcoes;


import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.mysql.jdbc.Blob;

import ufc.web.conexaoBD.ConnectionFactory;

	@SuppressWarnings("serial")
	public class JPEG extends HttpServlet implements Acao{  
	    public void executa(HttpServletRequest request, HttpServletResponse response) {  
	    	try {
	    	byte[] arquivo;
	        HttpSession ses = request.getSession();  
	        System.out.println(request.getParameter("id"));
	        String consulta = "select imagem from livro where id=?";
			Connection con = ConnectionFactory.getConnection();
			PreparedStatement pstmt;
		
	        Blob mapBlob = null;  
	        String contentType = "";  
	        String nomArquivo = "";  
	          
	        String cdArquivo = request.getParameter("id");  
	        pstmt = con.prepareStatement(consulta);
		  
	    pstmt.setInt(1,Integer.parseInt(cdArquivo));  
	    System.out.println("aantes");
	    ResultSet res = pstmt.executeQuery();
		System.out.println("depois");      
	    if (res.next()) { 
	    	
	       mapBlob = (Blob) res.getBlob("imagem");  
	    }             
	    res.getStatement().close();
	    
	    arquivo = mapBlob.getBytes(1,(new Long(mapBlob.length())).intValue());  
	    
	    response.setHeader("Cache-Control", "no-store");  
	    response.setHeader("Pragma", "no-cache");  
	    response.setDateHeader("Expires", 0);  
	    response.setContentType("image/jpeg");  
	  
	    ServletOutputStream out;
		try {
			out = response.getOutputStream();
		 
	    out.write(arquivo);  
	    out.flush();  
	    out.close();  
		} catch (IOException e) {
			
			e.printStackTrace();
		}          
	   
			con.close();
			pstmt.close();
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
	      
	}
	

}
